import unittest
import time
import os
from report import HTMLTestRunner


class run():
    def runtest(self):
        case_path = ".\\case\\web\\"
        result = ".\\report\\"
        test_case = self.Creatsuite(case_path)#所有test自动化用例

        #获取系统当前时间
        now = time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime(time.time()))
        day = time.strftime('%Y-%m-%d', time.localtime(time.time()))

        #定义个报告存放路径，支持相对路径
        tdresult = result + day

        if not os.path.exists(tdresult):
            os.mkdir(tdresult)

        filename = tdresult + "\\" + now + "_result.html"
        fp = open(filename, 'wb')
        #定义测试报告
        runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
                                                   title='测试报告',
                                                   description='执行情况：')
        #运行测试用例
        runner.run(test_case)
        fp.close()  #关闭报告文件

    def Creatsuite(self,case_path):
        # 定义单元测试容器
        testunit = unittest.TestSuite()

        # 定搜索用例文件的方法
        discover = unittest.defaultTestLoader.discover(case_path, pattern='*.py', top_level_dir=None)

        # 将测试用例加入测试容器中
        for test_suite in discover:
            for casename in test_suite:
                testunit.addTest(casename)
                # print testunit
        return testunit

if __name__ == "__main__":
    run().runtest()
